package com.meitutest.autoscript.fluency;


import android.support.test.uiautomator.By;
import android.support.test.uiautomator.UiDevice;
import android.util.Log;

import com.meitutest.autoscript.utils.TestReport;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by CrystalChen on 2017/1/4.
 */

public class DialogListener {
    static long PERIOD = 50;
    static long DELAY = 0;
    static Timer timer = null;
    static long startTime;
    static boolean isDeviceBusy=false;

    public static void startWatching(UiDevice uiDevice) {
        if (timer == null) {
            TestReport.i("DialogListener_startWatching: 已开启【弹窗】监听。");
            timer = new Timer();
            startTime = System.currentTimeMillis();
            DialogTimerTask task = new DialogTimerTask(uiDevice);
            timer.schedule(task, DELAY, PERIOD);
        } else {
            TestReport.i("DialogListener_startWatching: 【弹窗】监听已开启，无需重复开启！");
        }
    }

    public static void stopWatching() {
        if (timer != null) {
            TestReport.i("DialogListener_startWatching: 已终止【弹窗】监听。");
            timer.cancel();
        } else {
            TestReport.i("DialogListener_startWatching: 【弹窗】监听已终止，无需重复终止！");
        }
    }

    static class DialogTimerTask extends TimerTask {
        UiDevice mDevice;
        DialogTimerTask(UiDevice uiDevice){
            this.mDevice=uiDevice;
        }

        @Override
        public void run() {
//            if (mDevice.hasObject(By.text("同意|允许|以后再说|确定|以后再说|Ok|ok|OK|ALLOW|allow"))) {
//                mDevice.findObject(By.text("同意|允许|以后再说|确定|以后再说|Ok|ok|OK|ALLOW|allow")).click();
//                TestReport.i("MyWatcher_checkForCondition: 发现弹窗");
//            } else if (mDevice.hasObject(By.text("给我们评分"))) {
//                mDevice.findObject(By.text("不了，谢谢")).click();
//                TestReport.i("MyWatcher_checkForCondition: 发现弹窗-给我们评分，点击不了，谢谢");
//            }else
//            mDevice.waitForIdle();
            if(isDeviceBusy){
                Log.e("cxq", "DialogTimerTask_run: device is busy");
                return;
            }
            Log.e("cxq", "DialogTimerTask_run: "+mDevice.hasObject(By.text("同意")));
            if (mDevice.hasObject(By.text("同意"))) {
                mDevice.findObject(By.text("同意")).click();
                TestReport.i("MyWatcher_checkForCondition: 发现弹窗-淘宝责任弹窗，点击同意");
            }
            
        }
    }


}


